package com.yang.service.realm;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.yang.entity.Permissions;
import com.yang.entity.Roles;
import com.yang.entity.User;
import com.yang.service.UserService;

public class ShiroDbRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// 获取当前登录的用户名,等价于(String)principals.fromRealm(this.getName()).iterator().next()
		String currentUsername = (String) super.getAvailablePrincipal(principals);
		List<String> roleList = new ArrayList<String>();
		List<String> permissionList = new ArrayList<String>();
		// 从数据库中获取当前登录用户的详细信息
		User user = userService.getByUserName(currentUsername);
		if (null != user) {
			// 实体类User中包含有用户角色的实体类信息
			if (null != user.getRoles() && user.getRoles().size() > 0) {
				// 获取当前登录用户的角色
				for (Roles role : user.getRoles()) {
					roleList.add(role.getRolename());
					// 实体类Role中包含有角色权限的实体类信息
					if (null != role.getPermissions() && !role.getPermissions().isEmpty()) {
						// 获取权限
						for (Permissions pmss : role.getPermissions()) {
							if (!StringUtils.isEmpty(pmss.getpCode())) {
								permissionList.add(pmss.getpCode());
							}
						}
					}
				}
			}
		} else {
			throw new AuthorizationException();
		}
		// 为当前用户设置角色和权限
		SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
		simpleAuthorInfo.addRoles(roleList);
		simpleAuthorInfo.addStringPermissions(permissionList);
		// 实际中可能会像上面注释的那样从数据库取得
		return simpleAuthorInfo;
		// 若该方法什么都不做直接返回null的话,就会导致任何用户访问/admin/listUser.jsp时都会自动跳转到unauthorizedUrl指定的地址
		// 详见applicationContext.xml中的<bean id="shiroFilter">的配置
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		User user = userService.getByUserName(token.getUsername());
		if (user != null) {
			this.setSession("currentUser", user);
			return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), "");
		} else {
			return null;
		}
	}

	private void setSession(Object key, Object value) {
		Subject currSubject = SecurityUtils.getSubject();
		if (currSubject != null) {
			Session session = currSubject.getSession();
			System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");
			if (session != null) {
				session.setAttribute(key, value);
			}
		}
	}

}
